<?php
// 测试API调用的脚本

echo "=== 测试API调用 ===\n\n";

// 模拟菜品数据
$dishes = [
    ['id' => 198, 'name' => '广东红烧肉'],
    ['id' => 199, 'name' => '绝味川菜——豆花鱼片']
];

echo "模拟菜品数据:\n";
foreach ($dishes as $dish) {
    echo "  ID: {$dish['id']}, 名称: {$dish['name']}\n";
}

// 阿里云千问API配置
$apiKey = 'sk-416b931b781c420c9f6331b7346962b5';
$apiUrl = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
$model = 'qwen-plus';

// 构造菜品信息列表
$dishList = "";
foreach ($dishes as $dish) {
    $dishList .= "ID: {$dish['id']}, 名称: {$dish['name']}\n";
}

// 构造提示词
$prompt = "菜品信息列表：\n{$dishList}\n\n请根据这些菜品信息，为每个菜品提供以下信息：\n";
$prompt .= "1. 所需食材列表（包括食材名称和建议用量）\n";
$prompt .= "2. 烹饪时长（以分钟为单位）\n";
$prompt .= "3. 制作步骤（详细步骤）\n\n";
$prompt .= "请严格按照以下JSON格式返回结果，不要包含其他内容：\n";
$prompt .= "quantity全部采用g为后缀，没有其他重量方法\n";
$prompt .= "{\n";
$prompt .= "  \"菜品ID1\": {\n";
$prompt .= "    \"ingredients\": [\n";
$prompt .= "      {\"name\": \"鸡蛋\", \"quantity\": \"150g\"},\n";
$prompt .= "      {\"name\": \"西红柿\", \"quantity\": \"300g\"}\n";
$prompt .= "    ],\n";
$prompt .= "    \"cook_time\": \"7分钟\",\n";
$prompt .= "    \"steps\": \"1. 热锅凉油...\\n2. ...\"\n";
$prompt .= "  },\n";
$prompt .= "  \"菜品ID2\": {\n";
$prompt .= "    \"ingredients\": [...],\n";
$prompt .= "    \"cook_time\": \"...\",\n";
$prompt .= "    \"steps\": \"...\"\n";
$prompt .= "  }\n";
$prompt .= "}";

$data = [
    'model' => $model,
    'messages' => [
        [
            'role' => 'user',
            'content' => $prompt
        ]
    ],
    'temperature' => 0.1,
    'max_tokens' => 4000
];

echo "\n准备调用千问API:\n";
echo "URL: $apiUrl\n";
echo "模型: $model\n";
echo "菜品数量: " . count($dishes) . "\n";

// 发起HTTP请求
$headers = [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 60秒超时
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // 30秒连接超时

echo "\n正在发送请求...\n";
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);

echo "HTTP状态码: $httpCode\n";
if (!empty($error)) {
    echo "CURL错误: $error\n";
}

if (curl_errno($ch)) {
    $errorMsg = '千问API调用错误: ' . curl_error($ch);
    echo $errorMsg . "\n";
    curl_close($ch);
    exit(1);
}

curl_close($ch);

if ($httpCode !== 200) {
    $errorMsg = '千问API返回错误状态码: ' . $httpCode;
    echo $errorMsg . "\n";
    exit(1);
}

if (empty($response)) {
    $errorMsg = '千问API返回空响应';
    echo $errorMsg . "\n";
    exit(1);
}

echo "\nAPI响应:\n";
echo substr($response, 0, 500) . "...\n";

$responseArr = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    $errorMsg = '千问API响应JSON解析错误: ' . json_last_error_msg();
    echo $errorMsg . "\n";
    echo '响应内容: ' . $response . "\n";
    exit(1);
}

if (empty($responseArr['choices'][0]['message']['content'])) {
    $errorMsg = '千问API响应内容为空';
    echo $errorMsg . "\n";
    echo '完整响应: ' . json_encode($responseArr, JSON_UNESCAPED_UNICODE) . "\n";
    exit(1);
}

// 解析返回的JSON内容
$content = trim($responseArr['choices'][0]['message']['content']);
echo "\nAPI返回内容:\n";
echo $content . "\n";

// 尝试提取JSON部分
if (preg_match('/\{.*\}/s', $content, $matches)) {
    $jsonStr = $matches[0];
    $result = json_decode($jsonStr, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        echo "\n成功解析JSON数据:\n";
        echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    } else {
        $errorMsg = '提取的JSON内容解析失败: ' . json_last_error_msg();
        echo $errorMsg . "\n";
        echo '提取的JSON内容: ' . $jsonStr . "\n";
    }
} else {
    echo "无法从响应中提取有效的JSON数据\n";
}

echo "\n=== API测试完成 ===\n";
?>